package cn.com.nes.site.service.templatedesign.impl;


import cn.com.nes.common.util.OssUtil;
import cn.com.nes.common.util.ParameterUtil;
import cn.com.nes.mybatis.agent.templatedesign.mapper.HHousedesignMapper;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.vo.design.HHousedesignVo;
import cn.com.nes.site.service.templatedesign.HHousedesignService;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class HHousedesignServiceImpl implements HHousedesignService {
	private static int uid;
	@Resource
	private HHousedesignMapper housedesignMapper;
	@Resource
	private HHousemodelServiceImpl housemodelService;
	private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	;
	
	static {
		simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+0800"));
	}
	
	/**
	 * 查询订单池、我的订单、审核列表
	 *
	 * @param req
	 * @param
	 * @return
	 */
	@Override
	public PageData getCustomerClaim(DataReq req) throws ParseException {
		Integer pageId = ObjectUtil.isNull(ParameterUtil.getInteger(req, "pageid")) ? 1 : ParameterUtil.getInteger(req, "pageid");
		Integer pageSize = ObjectUtil.isNull(ParameterUtil.getInteger(req, "pagesize")) ? 10 : ParameterUtil.getInteger(req, "pagesize");
		String designid = ParameterUtil.getString(req, "designid");
		String sbcj = ParameterUtil.getString(req, "sbcj");
		String dah = ParameterUtil.getString(req, "dah");
		String name = ParameterUtil.getString(req, "name");
		String phone = ParameterUtil.getString(req, "phone");
		String status;
		String cardno = ParameterUtil.getString(req, "cardno");
		String xzqhdm = ParameterUtil.getString(req, "xzqhdm");
		String applytimebefore = ParameterUtil.getString(req, "applytimebefore");
		String applytimeafter = ParameterUtil.getString(req, "applytimeafter");
		//接单人订单池
		// TODO: 2023/10/16
		Integer receivinguser1 = ParameterUtil.getInteger(req, "receivinguser");
		status = ParameterUtil.getString(req, "status");
//		//标识，takeorders不为空mysql会查询固定条件
//		String takeOrders = null;
//		if (i != null) {
//			takeOrders = "接单了";
//		}
		Long receivinguser = null;
		if (Objects.nonNull(receivinguser1)) {
			receivinguser = Long.valueOf(receivinguser1);
		}
		//申请人订单池目前没有作用
		Integer applyuser1 = ParameterUtil.getInteger(req, "applyuser");
		Long applyuser = null;
		if (Objects.nonNull(applyuser1)) {
			applyuser = Long.valueOf(applyuser1);
		}
		//审核人订单池，只看待审核03
		Integer checkuser1 = ParameterUtil.getInteger(req, "checkuser");
		//设置审核人登录后只能查看待审核状态的订单
		String toBeReviewed = null;
		String showAll = "";
		if (checkuser1 != null) {
			toBeReviewed = "03";
			if (StringUtils.isEmpty(status)) {
				showAll = "11";
				
			}
		}
		Long checkuser = null;
		if (Objects.nonNull(checkuser1)) {
			checkuser = Long.valueOf(checkuser1);
		}
		//分页page类
		final Page<Map<String, Object>> page = new Page<>(pageId, pageSize);
		
		List<Map<String, Object>> orderList = housedesignMapper.selectListAsMap(page, designid, sbcj, applytimeafter, applytimebefore,
				dah, name, phone, status, cardno, xzqhdm, receivinguser, applyuser, checkuser, toBeReviewed, showAll);
		for (Map<String, Object> map : orderList) {
			String sta = (String) map.get("status");
			//通过code查找枚举类中的name
			String statusByCode = OrderStatus.getStatusByCode(sta);
			map.put("statusname", statusByCode);
			receivinguser = (Long) map.get("receivinguser");
			if (receivinguser != null) {
				//查找对应用户id的name
				String receivingusername = housedesignMapper.username(receivinguser);
				map.put("receivingusername", receivingusername);
			} else {
				map.put("receivingusername", "尚未有人接单");
			}
			if (Objects.nonNull(map.get("applytime"))) {
				Date applytime1 = (Date) map.get("applytime");
				//将date类型的时间戳转换成string类型
				String format = simpleDateFormat.format(applytime1);
				map.put("applytime", format);
			}
			sbcj = (String) map.get("sbcj");
			if (!StringUtils.isEmpty(sbcj)) {
				//查找对应用户id的name
				String getsbcjname = housedesignMapper.getsbcjname(sbcj);
				map.put("sbcjname", getsbcjname);
			}
		}
		page.setRecords(orderList);
		return PageData.ok(page);
	}
	
	/**
	 * 添加订单
	 *
	 * @return
	 */
	@Override
	public PageData addOrder(DataReq req) {
		String x =String.format("%06d", ++uid);
		Date currentDate = new Date();
		// 创建一个SimpleDateFormat对象，用于格式化日期
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		// 使用format方法将Date对象转换为字符串
		String formattedDate = dateFormat.format(currentDate);
		String Designid = "HX_000"+formattedDate+x;
		Integer housemodelid = ParameterUtil.getInteger(req, "housemodelid");
		String status = ParameterUtil.getString(req, "status");
		String dah = ParameterUtil.getString(req, "dah");
		String name = ParameterUtil.getString(req, "name");
		String address = ParameterUtil.getString(req, "address");
		String cardno = ParameterUtil.getString(req, "cardno");
		String sbcj = ParameterUtil.getString(req, "sbcj");
		String sbxh = ParameterUtil.getString(req, "sbxh");
		String phone = ParameterUtil.getString(req, "phone");
		String memo = ParameterUtil.getString(req, "memo");
		String applytime = ParameterUtil.getString(req, "applytime");
//		String sketchpath = ParameterUtil.getString(req, "sketchpath");
		String sketchfilename = ParameterUtil.getString(req, "sketchfilename");
		Integer applyuser = ParameterUtil.getInteger(req, "applyuser");
		Long appuser = null;
		if (applyuser != null) {
			appuser = Long.valueOf(applyuser);
		}
		String xzqhdm = ParameterUtil.getString(req, "xzqhdm");
		String modelname = ParameterUtil.getString(req, "modelname");
		String companyid = ParameterUtil.getString(req, "companyid");
		Integer sbsgjhId = ParameterUtil.getInteger(req, "sbsgjh_id");
		Long sbsgjd = null;
		if (sbsgjhId != null) {
			sbsgjd = Long.valueOf(sbsgjhId);
		}
		int count = housedesignMapper.count(cardno);
		if (count>0){
			return PageData.error("同一用户只能提交一次");
		}
		String devicedesignpath = housedesignMapper.selectdevicemodel(sbcj,sbxh);
		
		int i = housedesignMapper.addOrder(Designid, dah, name, cardno, phone, memo, xzqhdm, address, sbcj, appuser, sketchfilename, housemodelid, sbxh,
				sbsgjd, companyid,devicedesignpath);
		if (i == 0) {
			return PageData.error("添加失败");
		}
		return PageData.ok();
	}
	
	/**
	 * 订单详情
	 *
	 * @param req
	 * @return
	 */
	@Override
	public PageData orderDetails(DataReq req) {
		String designid = ParameterUtil.getString(req, "designid");
		List<Map<String, Object>> orderDetailsList = housedesignMapper.orderDetails(designid);
			for (Map<String, Object> orderDetails : orderDetailsList) {
//				订单状态
				String status1 = OrderStatus.getStatusByCode((String) orderDetails.get("status"));
				orderDetails.put("statusname", status1);
				
				
				//户型草图
				String sketchpath = (String) orderDetails.get("sketchfilename");
				if (!StringUtils.isEmpty(sketchpath)) {
//					对草图路径进行分割
					String[] split = sketchpath.split(";");
//					返回给前端列表类型的链接
					List sketchpathlist = new ArrayList();
					for (String s : split) {
						sketchpathlist.add(OssUtil.getImgSignURL(s, 0));
					}
					orderDetails.put("sketchpath", sketchpathlist);
				}
				//房屋设计
				String housedesignpath = (String) orderDetails.get("housedesignfilename");
				if (!StringUtils.isEmpty(housedesignpath)) {
					//同上
					String[] split2 = housedesignpath.split(";");
					//同上
					List housedesignpathlist = new ArrayList();
					for (String s : split2) {
						housedesignpathlist.add(OssUtil.getImgSignURL(s, 0));
					}
					orderDetails.put("housedesignpath", housedesignpathlist);
				}
				//设备设计图路径
				String devicedesignpath = (String) orderDetails.get("devicedesignfilename");
				if (!StringUtils.isEmpty(devicedesignpath)) {
					//同上
					String[] split3 = devicedesignpath.split(";");
					//同上
					List devicedesignpathlist = new ArrayList();
					for (String s : split3) {
						devicedesignpathlist.add(OssUtil.getImgSignURL(s, 0));
					}
					orderDetails.put("devicedesignpath", devicedesignpathlist);
				}
				//CAD模板
				String housedesignCADfilename = (String) orderDetails.get("housedesignCADfilename");
				if (!StringUtils.isEmpty(housedesignCADfilename)) {
					//同上
					String[] split3 = housedesignCADfilename.split(";");
					//同上
					List housedesignCADfile = new ArrayList();
					for (String s : split3) {
						housedesignCADfile.add(OssUtil.getFileSignURL(s, 0));
					}
					orderDetails.put("housedesignCADfile", housedesignCADfile);
				}
				
				//各个用户昵称
				Long receivinguser = (Long) orderDetails.get("receivinguser");
				if (receivinguser != null) {
//					根据用户id查询用户名
					String username = housedesignMapper.username(receivinguser);
					orderDetails.put("receivingusername", username);
				}
				Long checkuser = (Long) orderDetails.get("checkuser");
				if (checkuser != null) {
//					根据用户id查询用户名
					String checkusername = housedesignMapper.username(checkuser);
					orderDetails.put("checkusername", checkusername);
				}
				Long applyuser = (Long) orderDetails.get("applyuser");
				if (applyuser != null) {
//					根据用户id查询用户名
					String username = housedesignMapper.username(applyuser);
					orderDetails.put("applyusername", username);
				}
				//时间
				Date checktime = (Date) orderDetails.get("checktime");
				if (checktime != null) {
//					将时间转换成string类型
					orderDetails.put("checktime", simpleDateFormat.format(checktime));
				}
				Date receivingordertime = (Date) orderDetails.get("receivingordertime");
				if (receivingordertime != null) {
//					将时间转换成string类型
					orderDetails.put("receivingordertime", simpleDateFormat.format(receivingordertime));
				}
				Date completetime = (Date) orderDetails.get("completetime");
				if (completetime != null) {
//					将时间转换成string类型
					orderDetails.put("completetime", simpleDateFormat.format(completetime));
				}
				Date applytime = (Date) orderDetails.get("applytime");
				if (applytime != null) {
//					将时间转换成string类型
					orderDetails.put("applytime", simpleDateFormat.format(applytime));
				}
			}
			return PageData.ok(orderDetailsList);
	}
	
	/**
	 * 接单
	 *
	 * @param req
	 * @param
	 * @return
	 */
	@Override
	public PageData takeOrders(DataReq req) {
		Integer i1 = ParameterUtil.getInteger(req, "receivinguser");
		Long receivinguser = null;
		if (Objects.nonNull(i1)) {
			receivinguser = Long.valueOf(i1);
		}
		String designid = ParameterUtil.getString(req, "designid");
		int i = housedesignMapper.takeOrders(receivinguser, designid);
		return i == 0 ?
				       PageData.error("接单失败") : PageData.ok();
	}
	
	/**
	 * 删除订单
	 *
	 * @param req
	 * @param
	 * @return
	 */
	@Override
	public PageData deleteOrder(DataReq req) {
		String designid = ParameterUtil.getString(req, "designid");
		int i = housedesignMapper.deleteOrde(designid);
		return i == 0 ?
				       PageData.error("删除失败") : PageData.ok();
	}
	
	/**
	 * 施工进度查询
	 *
	 * @param req
	 * @param
	 * @return
	 */
	@Override
	public PageData progressQueries(DataReq req) {
		Integer pageId = ObjectUtil.isNull(ParameterUtil.getInteger(req, "pageid")) ? 1 : ParameterUtil.getInteger(req, "pageid");
		Integer pageSize = ObjectUtil.isNull(ParameterUtil.getInteger(req, "pagesize")) ? 10 : ParameterUtil.getInteger(req, "pagesize");
		String hzxm = ParameterUtil.getString(req, "hzxm");
		String xzqhdm = ParameterUtil.getString(req, "xzqhdm");
		String lzdh = ParameterUtil.getString(req, "lzdh");
		PageData res = new PageData();
		final Page<Map<String, Object>> page = new Page<>(pageId, pageSize);
		List<Map<String, Object>> maps = housedesignMapper.progressQueries(page, hzxm, xzqhdm, lzdh);
		for (Map<String, Object> map : maps) {
			String xz = (String) map.get("xzqhdm");
			String getsuperior = getsuperior(xz);
			map.put("xzqhmc", getsuperior);
		}
		page.setRecords(maps);
		return PageData.ok(page);
	}
	
	/**
	 * 通过xzqhdm拼接找到上级并拼接
	 * @param xzqhdm
	 * @return
	 */
	private String getsuperior(String xzqhdm) {
		boolean flag = true;
		Map xz = housedesignMapper.getsuperior(xzqhdm);
		if (Objects.nonNull(xz)) {
			StringBuilder restring = new StringBuilder((String) xz.get("xzqhmc"));
			if (!"86".equals(xz.get("sjqhdm"))) {
				Map<String, Object> getsuperior = null;
				while (flag) {
					String sjqhdm;
					if (Objects.isNull(getsuperior)) {
						sjqhdm = (String) xz.get("sjqhdm");
					} else {
						sjqhdm = (String) getsuperior.get("sjqhdm");
					}
					getsuperior = housedesignMapper.getsuperior(sjqhdm);
					restring.insert(0, getsuperior.get("xzqhmc"));
					if ("86".equals(getsuperior.get("sjqhdm"))) {
						return restring.toString();
					}
				}
			}
			return (String) xz.get("xzqhmc");
		}
		return "";
	}
	
	/**
	 * 设计结果上传
	 *
	 * @param req
	 * @return
	 */
	@Override
	public PageData outcome(DataReq req) {
		Integer i = ParameterUtil.getInteger(req, "receivinguser");
		Long receivinguser = null;
		if (Objects.nonNull(i)) {
			receivinguser = Long.valueOf(i);
		}
		String designid = ParameterUtil.getString(req, "designid");
		String housedesignfilename = ParameterUtil.getString(req, "housedesignfilename");
		String devicedesignfilename = ParameterUtil.getString(req, "devicedesignfilename");
		String housedesignCADfilename = ParameterUtil.getString(req, "housedesignCADfilename");
		String housedesignCADfiletxt = ParameterUtil.getString(req, "housedesignCADfiletxt");
		int x = housedesignMapper.outcome(receivinguser, housedesignfilename, devicedesignfilename, designid, housedesignCADfilename, housedesignCADfiletxt);
		return PageData.ok();
	}
	
	//订单审核
	@Override
	public PageData audit(DataReq req) {
		Integer check = ParameterUtil.getInteger(req, "checkuser");
		Long checkuser = null;
		if (Objects.nonNull(check)) {
			checkuser = Long.valueOf(check);
		}
		String checkresult = ParameterUtil.getString(req, "checkresult");
		String checkmemo = ParameterUtil.getString(req, "checkmemo");
		String designid = ParameterUtil.getString(req, "designid");
		String status;
		//设置审核结果状态码
		if ("通过".equals(checkresult)) {
			status = "05";
		} else {
			status = "04";
		}
		int i = housedesignMapper.audit(checkuser, checkresult, checkmemo, designid, status);
		return PageData.ok();
	}
	
	/**
	 * 退单
	 *
	 * @param req
	 * @return
	 */
	@Override
	public PageData chargebacks(DataReq req) {
		String string = ParameterUtil.getString(req, "designid");
		int i = housedesignMapper.chargebacks(string);
		if (i > 0) {
			return PageData.ok();
		}
		return null;
	}
	
	/**
	 * 订单池，我的订单，审核列表 测试用
	 *
	 * @param hHousedesignVo
	 * @return
	 */
	@Override
	public PageData ordersList(HHousedesignVo hHousedesignVo) {
		//接单人订单池
		// TODO: 2023/10/16
		Long receivinguser = hHousedesignVo.getReceivinguser();
		String takeOrders = null;
		if (receivinguser != null) {
			takeOrders = "接单了";
		}
		
		//申请人订单池不管状态
		Long applyuser = hHousedesignVo.getApplyuser();
		//审核人订单池，只看待审核03
		Long checkuser = hHousedesignVo.getCheckuser();
		if (checkuser != null) {
			hHousedesignVo.setStatus("03");
		}
		PageData res = new PageData();
//		final Page<Map<String, Object>> page = new Page<>(hHousedesignVo.getPageid(), hHousedesignVo.getPagesize());
		final Page<HHousedesignVo> page = new Page<>(hHousedesignVo.getPageid(), hHousedesignVo.getPagesize());
		List<HHousedesignVo> hHousedesignVoList = housedesignMapper.ordersList(page, hHousedesignVo);
		page.setRecords(hHousedesignVoList);
		return PageData.okPage(page);
	}
}

//订单状态枚举类
enum OrderStatus {
	APPLYING("01", "申请"),
	ORDERED("02", "已接单"),
	PENDING_REVIEW("03", "待审核"),
	REVIEW_FAILED("04", "审核不通过"),
	PUBLISHED("05", "已发布");
	
	private String code;
	private String status;
	
	OrderStatus(String code, String status) {
		this.code = code;
		this.status = status;
	}
	
	public String getCode() {
		return code;
	}
	
	public String getStatus() {
		return status;
	}
	
	public static Map getstatus() {
		Map map = new HashMap();
		for (OrderStatus value : OrderStatus.values()) {
			String code1 = value.getCode();
			String status1 = value.getStatus();
			map.put(code1, status1);
		}
		return map;
	}
	
	// 根据序号获取具体状态值
	public static String getStatusByCode(String code) {
		for (OrderStatus orderStatus : OrderStatus.values()) {
			if (orderStatus.getCode().equals(code)) {
				return orderStatus.getStatus();
			}
		}
		return null;
	}
}
